package com.zj.controller;

import com.zj.common.Msg;
import com.zj.common.Result;
import com.zj.common.Utility;
import com.zj.entity.User;
import com.zj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户控制器
 *
 * @author zzj
 * @date 2023/02/23
 */
@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping
    public Result userIsOnline(HttpServletRequest httpServletRequest){
        return  userService.userIsOnline(httpServletRequest.getSession());
    }

    /**
     * 用户登录
     *
     * @param request 请求
     * @param user    用户
     * @return {@code Result<User>}
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody User user){
        System.out.println(user);
        return userService.userLogin(request.getSession(),user);
    }

    /**
     * 注册
     *
     * @param user 用户
     * @return {@code Result}
     */
    @PostMapping("/register")
    public Result register( @RequestBody User user){
        //用户提交关键字段是否为空
        if (!Utility.strIsEmpty(user.getNumber()) && !Utility.strIsEmpty(user.getPassword())){
            //用户提交字段是否合规
            if (user.getNumber().length() >= 8 && user.getPassword().length() >= 8){
                return userService.userRegister(user);
            }
            return Result.error(Msg.USER_REGISTER_IS_SHORT);
        }
        return Result.error(Msg.USER_REGISTER_IS_NULL);
    }

}
